package leetcode.editor.cn;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 组合总和 II
 * @author qulq
 * @date 2024-07-07 14:12:50
 */
public class T40_CombinationSumIi{
	 public static void main(String[] args) {
	 	 //测试代码
	 	 Solution solution = new T40_CombinationSumIi().new Solution();
		 System.out.println(solution.combinationSum2(new int[]{10, 1, 2, 7, 6, 1, 5}, 8));
	 }
	 
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {

	List<List<Integer>> ans = new ArrayList<>();
	List<Integer> path = new ArrayList<>();
	boolean[] used;
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
		Arrays.sort(candidates);
		used = new boolean[candidates.length];
		backtracking(candidates, target, 0, 0);
		return ans;
    }

	private void backtracking(int[] candidates, int target, int start, int sum) {
		if (sum == target) {
			ans.add(new ArrayList<>(path));
			return;
		}
		for (int i = start; i < candidates.length && sum + candidates[i] <= target; i++) {
			// 去重的是同⼀树层上的“使⽤过”，同⼀树枝上的都是⼀个组合⾥的元素，不⽤去重
			// 树层去重的话，需要对数组排序！
			if (i > 0 && candidates[i - 1] == candidates[i] && used[i - 1] == false) {
				continue;
			}
			path.add(candidates[i]);
			used[i] = true;
			backtracking(candidates, target, i + 1, sum + candidates[i]);
			path.remove(path.size() - 1);
			used[i] = false;
		}
	}
}
//leetcode submit region end(Prohibit modification and deletion)

}